package framework.interceptors;

import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

public class UserSessionInterceptor extends HandlerInterceptorAdapter {
	private static final Log logger = LogFactory.getLog(UserSessionInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof ResourceHttpRequestHandler) {
			return true;
		}
		if (handler instanceof DefaultServletHttpRequestHandler) {
			return true;
		}
		logger.info("-preHandle------------ lan jie qi ");
		System.out.println(((HttpServletRequest) request).getRequestURL() + "               ----------------");
		/*
		 * if (StringUtils.isEmpty(((HttpServletRequest)
		 * request).getRequestURL())) { System.out.println(
		 * "1------------------ 空请求"); }
		 */

		  if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
	        	AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
	        	System.out.println("权限认证，authPassport="+authPassport);
	        	//没有声明需要权限,或者声明不验证权限
	       	 	if(authPassport != null ){
	       	 		System.out.println(authPassport.description());
	            	}   
		  }
		
		if (((HttpServletRequest) request).getRequestURL().lastIndexOf(".do") != -1) {
			logger.info(((HttpServletRequest) request).getRequestURL() + "?" + ((HttpServletRequest) request).getQueryString());
		}
		printParams(request);
		if (((HttpServletRequest) request).getRequestURL().lastIndexOf("login") != -1) {
			return super.preHandle(request, response, handler);
		}

	/*	String contextPath = NetworkUtils.getContextPath(request);
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(FrameworkConstans.USER_SESSION);
		if (user == null) {
			// response.sendRedirect(contextPath + "/index.jsp");
			// CookieUtils cookieUtils = new CookieUtils(request, response);
			// String userId =
			// cookieUtils.getCookieValue(FrameworkConstans.COOKIE_USER_ID);
			// String isUserIdRemember =
			// cookieUtils.getCookieValue(FrameworkConstans.IS_COOKIE_REMENBER);
			// request.setAttribute("userId", userId);
			// request.setAttribute("isUserIdRemember", isUserIdRemember);
			response.sendRedirect(contextPath + "/login/index.do");
			return false;
		}*/

		//ThreadLocalUser.setUser(user);

		// return super.preHandle(request, response, handler);

		return true;
	}

	private void printParams(HttpServletRequest request) {
		Map<String, String[]> parameterMap = request.getParameterMap();
		if (parameterMap == null || parameterMap.isEmpty())
			return;
		String line = "--> 下面是参数展示：";
		for (String key : parameterMap.keySet()) {
			String value = Arrays.toString(parameterMap.get(key));
			line += String.format(" %s:%s", key, value);
		}
		logger.info(line);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// logger.info("-postHandle------------ lan jie qi ");
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// logger.info("-afterCompletion------------ lan jie qi ");
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// logger.info("-afterConcurrentHandlingStarted------------ lan jie qi
		// ");
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

}
